<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="emit('update:visible', $event)"
    :title="dialogTitle"
    width="40%"
    :close-on-click-modal="false"
    :show-close="false"
    :close-on-press-escape="false"
  >
    <div class="progress-container">
      <el-progress 
        :percentage="progress" 
        :status="progressStatus"
        :stroke-width="16"
      />
      
      <div class="progress-details">
        <p>状态: {{ statusText }}</p>
        <p>文件: {{ processedFiles }}/{{ totalFiles }}</p>
        <p>大小: {{ formatSize(processedSize) }}/{{ formatSize(totalSize) }}</p>
        <p>速度: {{ formatSize(speed) }}/s</p>
        <p>预计剩余时间: {{ remainingTime }}</p>
      </div>
    </div>
    
    <template #footer>
      <el-button 
        v-if="progressStatus === 'success'"
        type="primary"
        @click="closeDialog"
      >
        完成
      </el-button>
      
      <el-button 
        v-else-if="progressStatus === 'exception'"
        type="danger"
        @click="retry"
      >
        重试
      </el-button>
      
      <el-button 
        v-else
        type="danger"
        :loading="isCancelling"
        @click="cancelTask"
      >
        {{ isCancelling ? '正在取消...' : '取消下载' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { getProgress, cancelTask as apiCancelTask } from '@/api/progress'

const props = defineProps({
  taskId: {
    type: String,
    required: true
  },
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '下载进度'
  }
})

const emit = defineEmits(['update:visible', 'retry'])

// 状态数据
const progress = ref(0)
const status = ref('pending')
const totalFiles = ref(0)
const processedFiles = ref(0)
const totalSize = ref(0)
const processedSize = ref(0)
const speed = ref(0)
const isCancelling = ref(false)
const lastUpdate = ref(Date.now())
const pollInterval = ref(null)

// 计算属性
const progressStatus = computed(() => {
  switch (status.value) {
    case 'completed': return 'success'
    case 'failed': return 'exception'
    case 'cancelled': return 'exception'
    default: return ''
  }
})

const statusText = computed(() => {
  switch (status.value) {
    case 'pending': return '准备中...'
    case 'processing': return '处理中...'
    case 'completed': return '已完成'
    case 'failed': return '下载失败'
    case 'cancelled': return '已取消'
    default: return status.value
  }
})

const dialogTitle = computed(() => {
  return `${props.title} (${progress.value}%)`
})

const remainingTime = computed(() => {
  if (speed.value <= 0 || progress.value >= 100) return '--'
  
  const remainingBytes = totalSize.value - processedSize.value
  const seconds = Math.round(remainingBytes / speed.value)
  
  if (seconds < 60) return `${seconds}秒`
  return `${Math.floor(seconds / 60)}分${seconds % 60}秒`
})

// 方法
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const closeDialog = () => {
  emit('update:visible', false)
}

const retry = () => {
  emit('retry')
  closeDialog()
}

const cancelTask = async () => {
  try {
    isCancelling.value = true
    await apiCancelTask(props.taskId)
    status.value = 'cancelled'
    ElMessage.success('下载已取消')
  } catch (error) {
    ElMessage.error('取消下载失败')
  } finally {
    isCancelling.value = false
  }
}

const updateProgress = async () => {
  try {
    const res = await getProgress(props.taskId)
    
    if (res.data.success) {
      const data = res.data.data
      progress.value = data.progress
      status.value = data.status
      totalFiles.value = data.totalFiles
      processedFiles.value = data.processedFiles
      totalSize.value = data.totalSize
      processedSize.value = data.processedSize
      // 直接使用服务器返回的速度
      speed.value = data.speed
      lastUpdate.value = Date.now()
      
      // 如果任务完成或失败，停止轮询
      if (['completed', 'failed', 'cancelled'].includes(data.status)) {
        clearInterval(pollInterval.value)
      }
    }
  } catch (error) {
    console.error('获取进度失败:', error)
    status.value = 'failed'
    clearInterval(pollInterval.value)
  }
}

// 生命周期
onMounted(() => {
  // 开始轮询进度
  updateProgress()
  pollInterval.value = setInterval(updateProgress, 2000) // 每2秒更新一次
})

onBeforeUnmount(() => {
  clearInterval(pollInterval.value)
})
</script>

<style scoped>
.progress-container {
  padding: 20px;
}

.progress-details {
  margin-top: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.progress-details p {
  margin: 8px 0;
}
</style>